<template>
  <view class="order-detail">
    <!-- 导航栏 -->
    <NavBar title="订单详情" />

    <!-- 订单状态 -->
    <view class="status-section" :class="getStatusClass(orderDetail.status)">
      <view class="status-text">{{ getStatusText(orderDetail.status) }}</view>
      <view class="status-desc">{{ getStatusDesc(orderDetail.status) }}</view>
    </view>

    <!-- 收货地址 -->
    <view class="address-section">
      <view class="address-info">
        <view class="address-header">
          <text class="name">{{ orderDetail.address?.name }}</text>
          <text class="phone">{{ orderDetail.address?.phone }}</text>
        </view>
        <view class="address-detail">
          {{ getFullAddress(orderDetail.address) }}
        </view>
      </view>
      <Location size="20" class="address-icon" />
    </view>

    <!-- 订单信息 -->
    <view class="order-info-section">
      <view class="section-title">订单信息</view>
      <view class="info-item">
        <text class="label">订单编号</text>
        <view class="value-copy">
          <text class="value">{{ orderDetail.orderNo }}</text>
          <nut-button size="small" type="primary" @click="copyOrderNo">复制</nut-button>
        </view>
      </view>
      <view class="info-item">
        <text class="label">创建时间</text>
        <text class="value">{{ orderDetail.createTime }}</text>
      </view>
      <view class="info-item" v-if="orderDetail.payTime">
        <text class="label">支付时间</text>
        <text class="value">{{ orderDetail.payTime }}</text>
      </view>
      <view class="info-item" v-if="orderDetail.shipTime">
        <text class="label">发货时间</text>
        <text class="value">{{ orderDetail.shipTime }}</text>
      </view>
      <view class="info-item" v-if="orderDetail.confirmTime">
        <text class="label">收货时间</text>
        <text class="value">{{ orderDetail.confirmTime }}</text>
      </view>
      <view class="info-item">
        <text class="label">支付方式</text>
        <text class="value">{{ getPaymentMethod(orderDetail.payMethod) }}</text>
      </view>
      <view class="info-item" v-if="orderDetail.remark">
        <text class="label">订单备注</text>
        <text class="value">{{ orderDetail.remark }}</text>
      </view>
    </view>

    <!-- 商品信息 -->
    <view class="goods-section">
      <view class="section-title">商品信息</view>
      <view class="goods-list">
        <view class="goods-item" v-for="(item, index) in orderDetail.goods" :key="index">
          <image :src="item.goods.cover" class="goods-image" @click="previewImage(item.goods.cover)" />
          <view class="goods-info">
            <text class="goods-name">{{ item.goods.title }}</text>
            <text class="goods-sku" v-if="item.skuText">{{ item.skuText }}</text>
            <view class="goods-price-qty">
              <nut-price :price="item.price" size="normal" />
              <text class="goods-qty">x{{ item.quantity }}</text>
            </view>
          </view>
        </view>
      </view>
    </view>

    <!-- 金额信息 -->
    <view class="amount-section">
      <view class="amount-item">
        <text>商品金额</text>
        <nut-price :price="orderDetail.goodsAmount" size="normal" />
      </view>
      <view class="amount-item">
        <text>运费</text>
        <nut-price :price="orderDetail.freightAmount" size="normal" />
      </view>
      <view class="amount-item" v-if="orderDetail.discountAmount > 0">
        <text>优惠</text>
        <text class="discount">-<nut-price :price="orderDetail.discountAmount" size="normal" /></text>
      </view>
      <view class="amount-total">
        <text>实付款</text>
        <nut-price :price="orderDetail.payAmount" size="large" class="total-price" />
      </view>
    </view>

    <!-- 物流信息 -->
    <view class="logistics-section" v-if="orderDetail.status >= 2 && orderDetail.status <= 4">
      <view class="section-title">物流信息</view>
      <view v-if="logistics.length > 0" class="logistics-info">
        <view class="logistics-company">
          <text>{{ logistics.company }}</text>
          <text class="logistics-no">{{ logistics.logisticsNo }}</text>
        </view>
        <view class="logistics-timeline">
          <view class="timeline-item" v-for="(item, index) in logistics.traces" :key="index">
            <view class="timeline-dot" :class="{ 'active': index === 0 }"></view>
            <view class="timeline-content">
              <view class="timeline-message">{{ item.content }}</view>
              <view class="timeline-time">{{ item.time }}</view>
            </view>
          </view>
        </view>
      </view>
      <view v-else class="empty-logistics">
        <text>暂无物流信息</text>
      </view>
    </view>

    <!-- 底部操作栏 -->
    <view class="bottom-action" v-if="showBottomAction">
      <!-- 待付款 -->
      <template v-if="orderDetail.status === 1">
        <nut-button size="small" @click="cancelOrder">取消订单</nut-button>
        <nut-button size="small" type="primary" @click="payOrder">去支付</nut-button>
      </template>

      <!-- 待发货 -->
      <template v-else-if="orderDetail.status === 2">
        <nut-button size="small" @click="contactService">联系客服</nut-button>
      </template>

      <!-- 待收货 -->
      <template v-else-if="orderDetail.status === 3">
        <nut-button size="small" @click="viewLogistics">查看物流</nut-button>
        <nut-button size="small" type="primary" @click="confirmReceive">确认收货</nut-button>
      </template>

      <!-- 待评价 -->
      <template v-else-if="orderDetail.status === 4">
        <nut-button size="small" @click="viewLogistics">查看物流</nut-button>
        <nut-button size="small" type="primary" @click="goToReview">去评价</nut-button>
      </template>

      <!-- 已完成 -->
      <template v-else-if="orderDetail.status === 5">
        <nut-button size="small" @click="deleteOrder">删除订单</nut-button>
        <nut-button size="small" type="primary" @click="rebuyOrder">再次购买</nut-button>
      </template>

      <!-- 已取消 -->
      <template v-else-if="orderDetail.status === 0">
        <nut-button size="small" @click="deleteOrder">删除订单</nut-button>
      </template>
    </view>
  </view>
</template>

<script setup lang="ts">
import { ref, computed, onMounted } from 'vue'
import Taro from '@tarojs/taro'
import { Location } from '@nutui/icons-vue-taro'
import NavBar from '../../components/NavBar/index.vue'
import orderApi from '../../api/order'

// 获取订单ID
const orderId = Taro.getCurrentInstance().router?.params.id

// 订单详情
const orderDetail = ref({
  id: '',
  orderNo: '',
  status: 0,
  totalAmount: '0.00',
  payAmount: '0.00',
  goodsAmount: '0.00',
  freightAmount: '0.00',
  discountAmount: '0.00',
  createTime: '',
  payTime: '',
  shipTime: '',
  confirmTime: '',
  payMethod: 0,
  remark: '',
  address: {
    name: '',
    phone: '',
    province: '',
    city: '',
    district: '',
    detail: ''
  },
  goods: []
})

// 物流信息
const logistics = ref({
  company: '',
  logisticsNo: '',
  traces: []
})

// 是否显示底部操作栏
const showBottomAction = computed(() => {
  return [0, 1, 2, 3, 4, 5].includes(orderDetail.value.status)
})

// 获取订单状态文本
const getStatusText = (status) => {
  const statusTexts = {
    0: '已取消',
    1: '待付款',
    2: '待发货',
    3: '待收货',
    4: '待评价',
    5: '已完成'
  }
  return statusTexts[status] || '未知状态'
}

// 获取订单状态描述
const getStatusDesc = (status) => {
  const statusDescs = {
    0: '订单已取消',
    1: '请尽快完成支付',
    2: '商家正在备货中',
    3: '商品已发出，请注意查收',
    4: '期待您的评价',
    5: '订单已完成'
  }
  return statusDescs[status] || ''
}

// 获取状态样式类
const getStatusClass = (status) => {
  return `status-${status}`
}

// 获取支付方式文本
const getPaymentMethod = (method) => {
  const methods = {
    1: '微信支付',
    2: '支付宝',
    3: '银行卡',
    0: '未支付'
  }
  return methods[method] || '其他'
}

// 获取完整地址
const getFullAddress = (address) => {
  if (!address) return ''
  return `${address.province}${address.city}${address.district}${address.detail}`
}

// 复制订单号
const copyOrderNo = () => {
  Taro.setClipboardData({
    data: orderDetail.value.orderNo,
    success: () => {
      Taro.showToast({
        title: '复制成功',
        icon: 'success'
      })
    }
  })
}

// 预览图片
const previewImage = (image) => {
  Taro.previewImage({
    urls: [image],
    current: image
  })
}

// 取消订单
const cancelOrder = () => {
  Taro.showModal({
    title: '提示',
    content: '确定要取消该订单吗？',
    success: (res) => {
      if (res.confirm) {
        orderApi.cancelOrder(orderDetail.value.id).then(() => {
          Taro.showToast({
            title: '订单已取消',
            icon: 'success'
          })
          fetchOrderDetail()
        }).catch(err => {
          Taro.showToast({
            title: err.message || '取消订单失败',
            icon: 'none'
          })
        })
      }
    }
  })
}

// 支付订单
const payOrder = () => {
  Taro.navigateTo({
    url: `/pages/order/payment?id=${orderDetail.value.id}&amount=${orderDetail.value.payAmount}`
  })
}

// 查看物流
const viewLogistics = () => {
  Taro.navigateTo({
    url: `/pages/order/logistics?id=${orderDetail.value.id}`
  })
}

// 确认收货
const confirmReceive = () => {
  Taro.showModal({
    title: '提示',
    content: '确认已收到商品吗？',
    success: (res) => {
      if (res.confirm) {
        orderApi.confirmOrder(orderDetail.value.id).then(() => {
          Taro.showToast({
            title: '已确认收货',
            icon: 'success'
          })
          fetchOrderDetail()
        }).catch(err => {
          Taro.showToast({
            title: err.message || '确认收货失败',
            icon: 'none'
          })
        })
      }
    }
  })
}

// 去评价
const goToReview = () => {
  Taro.navigateTo({
    url: `/pages/order/review?id=${orderDetail.value.id}`
  })
}

// 删除订单
const deleteOrder = () => {
  Taro.showModal({
    title: '提示',
    content: '确定要删除该订单吗？',
    success: (res) => {
      if (res.confirm) {
        orderApi.deleteOrder(orderDetail.value.id).then(() => {
          Taro.showToast({
            title: '订单已删除',
            icon: 'success'
          })
          Taro.navigateBack()
        }).catch(err => {
          Taro.showToast({
            title: err.message || '删除订单失败',
            icon: 'none'
          })
        })
      }
    }
  })
}

// 再次购买
const rebuyOrder = () => {
  orderApi.rebuyOrder(orderDetail.value.id).then(() => {
    Taro.switchTab({
      url: '/pages/cart/index'
    })
  }).catch(err => {
    Taro.showToast({
      title: err.message || '操作失败',
      icon: 'none'
    })
  })
}

// 联系客服
const contactService = () => {
  // 实际应用中可能会有客服联系方式
  Taro.showToast({
    title: '客服功能开发中',
    icon: 'none'
  })
}

// 获取订单详情
const fetchOrderDetail = () => {
  if (!orderId) return
  
  orderApi.getOrderDetail(orderId).then(res => {
    orderDetail.value = res.data
  }).catch(err => {
    Taro.showToast({
      title: err.message || '获取订单详情失败',
      icon: 'none'
    })
  })
}

// 获取物流信息
const fetchLogistics = () => {
  if (!orderId) return
  
  orderApi.getOrderLogistics(orderId).then(res => {
    logistics.value = res.data
  }).catch(err => {
    console.error('获取物流信息失败', err)
  })
}

// 页面加载
onMounted(() => {
  fetchOrderDetail()
  fetchLogistics()
})
</script>

<style lang="scss">
.order-detail {
  min-height: 100vh;
  background-color: #f5f5f5;
  padding-bottom: 60px;
}

.status-section {
  padding: 20px 16px;
  color: #fff;
  
  &.status-0 {
    background-color: #999; // 已取消
  }
  
  &.status-1 {
    background-color: #ff6b00; // 待付款
  }
  
  &.status-2 {
    background-color: #2196f3; // 待发货
  }
  
  &.status-3 {
    background-color: #ff9800; // 待收货
  }
  
  &.status-4 {
    background-color: #8bc34a; // 待评价
  }
  
  &.status-5 {
    background-color: #999; // 已完成
  }
  
  .status-text {
    font-size: 18px;
    font-weight: bold;
    margin-bottom: 5px;
  }
  
  .status-desc {
    font-size: 14px;
    opacity: 0.8;
  }
}

.address-section {
  position: relative;
  background-color: #fff;
  margin: 10px 0;
  padding: 16px;
  
  .address-info {
    .address-header {
      margin-bottom: 8px;
      
      .name {
        font-size: 16px;
        font-weight: bold;
        margin-right: 10px;
      }
      
      .phone {
        color: #666;
      }
    }
    
    .address-detail {
      font-size: 14px;
      color: #333;
      line-height: 1.4;
    }
  }
  
  .address-icon {
    position: absolute;
    left: 16px;
    top: 50%;
    transform: translateY(-50%);
    display: none; // 暂时隐藏，根据设计调整
  }
}

.order-info-section,
.goods-section,
.amount-section,
.logistics-section {
  background-color: #fff;
  margin-bottom: 10px;
  padding: 16px;
}

.section-title {
  font-size: 14px;
  font-weight: bold;
  margin-bottom: 10px;
  color: #333;
}

.order-info-section {
  .info-item {
    display: flex;
    justify-content: space-between;
    margin-bottom: 10px;
    font-size: 14px;
    
    &:last-child {
      margin-bottom: 0;
    }
    
    .label {
      color: #666;
    }
    
    .value {
      color: #333;
    }
    
    .value-copy {
      display: flex;
      align-items: center;
      
      .nut-button {
        margin-left: 10px;
        padding: 0 8px;
        height: 24px;
        line-height: 24px;
      }
    }
  }
}

.goods-section {
  .goods-list {
    .goods-item {
      display: flex;
      margin-bottom: 10px;
      
      &:last-child {
        margin-bottom: 0;
      }
      
      .goods-image {
        width: 80px;
        height: 80px;
        border-radius: 4px;
        flex-shrink: 0;
      }
      
      .goods-info {
        flex: 1;
        margin-left: 10px;
        display: flex;
        flex-direction: column;
        justify-content: space-between;
        
        .goods-name {
          font-size: 14px;
          line-height: 1.4;
          overflow: hidden;
          text-overflow: ellipsis;
          display: -webkit-box;
          -webkit-line-clamp: 2;
          -webkit-box-orient: vertical;
        }
        
        .goods-sku {
          font-size: 12px;
          color: #999;
          margin: 4px 0;
        }
        
        .goods-price-qty {
          display: flex;
          justify-content: space-between;
          align-items: center;
          
          .goods-qty {
            font-size: 12px;
            color: #999;
          }
        }
      }
    }
  }
}

.amount-section {
  .amount-item {
    display: flex;
    justify-content: space-between;
    margin-bottom: 10px;
    font-size: 14px;
    color: #666;
    
    .discount {
      color: #ff5000;
    }
  }
  
  .amount-total {
    display: flex;
    justify-content: space-between;
    padding-top: 10px;
    border-top: 1px solid #f5f5f5;
    font-size: 14px;
    
    .total-price {
      color: #ff5000;
      font-weight: bold;
    }
  }
}

.logistics-section {
  .logistics-info {
    .logistics-company {
      display: flex;
      justify-content: space-between;
      margin-bottom: 15px;
      font-size: 14px;
      
      .logistics-no {
        color: #666;
      }
    }
    
    .logistics-timeline {
      .timeline-item {
        position: relative;
        padding-left: 20px;
        padding-bottom: 15px;
        
        &:last-child {
          padding-bottom: 0;
        }
        
        &:not(:last-child)::before {
          content: '';
          position: absolute;
          left: 6px;
          top: 10px;
          bottom: 0;
          width: 1px;
          background-color: #ddd;
        }
        
        .timeline-dot {
          position: absolute;
          left: 0;
          top: 6px;
          width: 12px;
          height: 12px;
          border-radius: 50%;
          background-color: #ddd;
          
          &.active {
            background-color: #fa2c19;
          }
        }
        
        .timeline-content {
          .timeline-message {
            font-size: 14px;
            line-height: 1.4;
            margin-bottom: 4px;
          }
          
          .timeline-time {
            font-size: 12px;
            color: #999;
          }
        }
      }
    }
  }
  
  .empty-logistics {
    padding: 20px 0;
    text-align: center;
    color: #999;
  }
}

.bottom-action {
  position: fixed;
  bottom: 0;
  left: 0;
  right: 0;
  height: 50px;
  background-color: #fff;
  display: flex;
  justify-content: flex-end;
  align-items: center;
  padding: 0 16px;
  box-shadow: 0 -2px 10px rgba(0, 0, 0, 0.05);
  
  .nut-button {
    margin-left: 10px;
  }
}
</style>